from PySide6.QtCore import QObject
from .webview_queue_sqlite_operations import WebViewQueueSqliteOperations
from .base_webview_bridge import BaseWebViewBridge
from typing import List
from PySide6.QtWebChannel import QWebChannel


class WebviewController(QObject):
    def __init__(
        self,
        web_engine_page,
        webview_bridge_list: List[type[BaseWebViewBridge]],
        web_webview,
        scheduler,
        parent=None,
    ):
        super().__init__(parent)
        self.page = web_engine_page
        self.bridge_instances = {}

        # 创建bridge实例并保存
        for bridge_class in webview_bridge_list:
            instance = bridge_class(web_webview)
            bridge_name = bridge_class.__name__.lower()
            setattr(self, bridge_name, instance)
            self.bridge_instances[bridge_name] = instance

        self.queue_sqlite_operations = WebViewQueueSqliteOperations(
            web_webview, scheduler
        )
        self.channel = QWebChannel()

        # 使用已创建的实例注册到channel
        for bridge_name, instance in self.bridge_instances.items():
            self.channel.registerObject(bridge_name, instance)

        # 为了向前兼容，确保注册名为 "entrance" 的对象
        if "webviewbridge" in self.bridge_instances:
            self.channel.registerObject(
                "entrance", self.bridge_instances["webviewbridge"]
            )

        self.channel.registerObject("queueSqlite", self.queue_sqlite_operations)
        self.page.setWebChannel(self.channel)
